package com.google.code.syncgear.plugin;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import com.google.code.syncgear.core.exception.FetchException;
import com.google.code.syncgear.plugin.bean.FetchResult;

public abstract class AbstractFetch implements Serializable {

	private static final long serialVersionUID = 1807336831540171077L;
	
	private static final int MAX_RECONNECT_TIMES = 3;

	private int reconnectTimes = 0;
	
	public abstract List<FetchResult> fire(List<String> source) throws FetchException;
	
	protected InputStream getInputStream(String url) throws IOException {
		InputStream inputStream = null;
		try {
			this.reconnectTimes = 0;
			inputStream = getInputStreamSafe(url);
		} catch (MalformedURLException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		}
		return inputStream;
	}
	
	private InputStream getInputStreamSafe(String url) throws IOException {
		reconnectTimes++;
		InputStream inputStream = null;
		try {
			inputStream = ((HttpURLConnection) (new URL(url)).openConnection()).getInputStream();
		} catch (MalformedURLException e) {
			throw e;
		} catch (IOException e) {
			if(reconnectTimes < MAX_RECONNECT_TIMES) {
				inputStream = getInputStreamSafe(url);
			} else
				throw e;
		}
		return inputStream;
	}

}
